package com.ylp.web.server;

import com.ylp.web.servlet.DispatcherServlet;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;

/**
 * @description:
 * @date: 2019/9/13 18:40.
 * @author: yulipeng.
 */
public class TomcatServer {

    private Tomcat tomcat;

    private String[] args;

    public TomcatServer(String[] args){
        this.args = args;
    }

    public void startServer() throws LifecycleException {
        tomcat = new Tomcat();
        tomcat.setPort(7999);
        tomcat.start();

        Context context = new StandardContext();
        context.setPath("");
        context.addLifecycleListener(new Tomcat.FixContextListener());

        DispatcherServlet servlet = new DispatcherServlet();
        Tomcat.addServlet(context, "dispatchServlet", servlet).setAsyncSupported(true);
        context.addServletMappingDecoded("/", "dispatchServlet");
        tomcat.getHost().addChild(context);

        // 设置常驻线程，防止中途退出；
        Thread awaitThread = new Thread("tomcat-thread-await"){
            @Override
            public void run(){
                TomcatServer.this.tomcat.getServer().await();
            }
        };
        // 非守护线程
        awaitThread.setDaemon(false);
        awaitThread.start();
    }
}
